﻿
using System.Linq;
using SmallShop.Frame;
using SmalShop.Model;

namespace SmallShop.Bll
{
    /// <summary>
    /// 产品类型逻辑
    /// </summary>
    public class CategoryBiz: BaseBiz<CategoryModel>
    {
        public override ResultModel Add(CategoryModel model)
        {
            string msg;
            if (!CheckModel(model, out msg))
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg };
            }
            var count = Query(it => it.Title == model.Title).Count();
            if (count > 0)
            {
                return new ResultModel { Code = ResultModel.Failure, Message = "已有该类型" };
            }
            return base.Add(model);
        }


        public override ResultModel Update(CategoryModel model)
        {
            var msg = "无效的修改数据";
            if (model.Id < 1 || !CheckModel(model, out msg))
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg };
            }
            var m = Query().SingleOrDefault(it => it.Id == model.Id);
            if (m == null)
            {
                return new ResultModel { Code = ResultModel.InValid, Message = msg };
            }
            var p = Query(it => it.Title == model.Title).FirstOrDefault();
            if (p != null && p.Id != model.Id)
            {
                return new ResultModel { Code = ResultModel.Failure, Message = "重名了" };
            }
            m.Title = model.Title;
            return base.Update(m);
        }

        public static bool CheckModel(CategoryModel model, out string msg)
        {
            msg = null;
            if (model.Title.IsNullOrEmpty())
            {
                msg = "无效的名称";
                return false;
            }
 
            return true;
        }
    }
}
